package com.seeTools.next.common.tools;

/**
 * @Author: seeTools
 * @Date: 2024/5/22  11:29
 * @Version 1.0
 */

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaotong
 */
@Component
public class FeishuUtils {

    private static final String COMPANY = "媄俪科技";
    private static final String FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/12871db1-6619-4566-b7ae-3bbac08e940c";
    private static final String FEISHU_SECRET = "oivX08P09xq1yoowYwsD7d";
    private static String env;
    private static StringRedisTemplate stringRedisTemplate;

    /**
     * 发送简单的文本消息
     *
     * @param message
     */
    public static void sendSimpleMessage(String message) {
        // 重复的消息设置一个简单的过滤，1分钟之内，重复的消息只推送一次
        String sendLimitCheckKey = "feishuLimit:" + DigestUtil.md5Hex(message);
        Boolean hasKey = stringRedisTemplate.hasKey(sendLimitCheckKey);
        if (hasKey == null || !hasKey) {
            // 获取当前登入的租户
            stringRedisTemplate.opsForValue().set(sendLimitCheckKey, message, 1L, TimeUnit.MINUTES);
            String serverName = ("prod".equals(env) || "pro".equals(env)) ? "正式环境" : "测试环境";
            message = COMPANY + "【" + serverName + "】：" + message;
            Long timestamp = System.currentTimeMillis() / 1000;
            JSONObject param = new JSONObject();
            String sign = null;
            try {
                sign = getSign(timestamp);
            } catch (Exception e) {
                e.printStackTrace();
            }
            param.set("msg_type", "text");
            param.set("timestamp", timestamp);
            param.set("sign", sign);
            JSONObject text = new JSONObject();
            text.set("text", message);
            param.set("content", text);
        }
    }

    /**
     * 获取签名
     *
     * @return
     * @throws Exception
     */
    private static String getSign(Long timestamp) throws Exception {
        String secret = FEISHU_SECRET;
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(), "HmacSHA256"));
        byte[] signData = mac.doFinal();
        return Base64.encodeBase64String(signData);
    }

    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        FeishuUtils.env = env;
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        FeishuUtils.stringRedisTemplate = stringRedisTemplate;
    }
}
